/*
 * Copyright 2010 Original Author(s)
 * 
 * This file is part of Kommando
 * 
 * Kommando is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Kommando is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Kommando.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.kommando.web.google.translate.actions.support;

import java.util.Locale;

import org.kommando.core.action.AbstractAction;
import org.kommando.core.action.Action;
import org.kommando.core.action.ActionExecutionException;
import org.kommando.core.catalog.CatalogObject;
import org.kommando.core.catalog.TextObject;

import com.google.api.translate.Language;

/**
 * Support {@link Action} for translations.
 * 
 * @author Peter De Bruycker
 */
public abstract class BaseTranslateAction extends AbstractAction {

    @Override
    public Class<?>[] getIndirectTypes() {
        return new Class<?>[] { String.class };
    }

    @Override
    public CatalogObject getDefaultIndirectObjectValue(CatalogObject ignored) {
        return new TextObject(Locale.getDefault().getLanguage());
    }

    @Override
    public boolean isIndirectMandatory(CatalogObject direct) {
        return true;
    }

    @Override
    public CatalogObject execute(CatalogObject direct, CatalogObject indirect) throws ActionExecutionException {
        String language = indirect.getExtension(String.class);

        String[] languages = language.split(" ");

        Language from;
        Language to;

        if (languages.length == 1) {
            from = Language.AUTO_DETECT;
            to = Language.fromString(language);
        } else {
            from = Language.fromString(languages[0]);
            to = Language.fromString(languages[1]);
        }

        if (from == null || to == null) {
            // TODO show warning to user
            return null;
        }

        return doExecute(direct, from, to);
    }

    protected abstract CatalogObject doExecute(CatalogObject direct, Language from, Language to) throws ActionExecutionException;

}
